package com.bing.utils;

/**
 * ip 转换工具
 * Created by kaibb on 15-11-25.
 */
public class IpTool {
    /**
     * 将字符串IP形式转换成对应256进制long类型, eg. 216.239.39.1 --> 3639551745L
     *
     * @param ip
     * @return 数字
     */
    public static long ip2Long(String ip) {
        String[] ips = ip.split("\\.");
        Long[] ipLong = new Long[4];
        for (int i = 0, len = ips.length; i < len; i++) {
            ipLong[i] = Long.parseLong(ips[i]);
        }
        long result = ipLong[3] & 0xFF;
        result |= ((ipLong[2] << 8)) & 0xFF00;
        result |= ((ipLong[1] << 16)) & 0xFF0000;
        result |= ((ipLong[0] << 24)) & 0xFF000000;
        return result;
    }

    /**
     * 将long类型转换成字符串类型IP,  eg. 3639551745L --> 216.239.39.1
     *
     * @param ip
     * @return
     */
    public static String long2Ip(long ip) {
        StringBuilder sb = new StringBuilder();
        sb.append((ip >> 24) & 0xFF).append(".");
        sb.append((ip >> 16) & 0xFF).append(".");
        sb.append((ip >> 8) & 0xFF).append(".");
        sb.append(ip & 0xFF);
        return sb.toString();
    }

    /**
     * 获取掩码的反码, eg. if revert==true 20 --> {0,0,15,255} ; else  20 --> {255,255,240,0}
     *
     * @param length 网络ID位数
     * @return
     */
    public static int[] getMask(int length, boolean revert) {
        int binaryMask = 0xFFFFFFFF << (32 - length);
        if (revert) {
            binaryMask = binaryMask ^ 0xFFFFFFFF;
        }
        int[] marks = new int[4];
        for (int shift = 24, k = 0; shift > 0; shift -= 8) {
            marks[k] = (binaryMask >>> shift) & 0xFF;
            k++;
        }
        marks[3] = binaryMask & 0xFF;
        return marks;
    }


    public static String getIP(String ips, boolean max) {
        String[] _ip = ips.split("/");
        String[] ip = _ip[0].split("\\.");
        int masks[] = getMask(Integer.valueOf(_ip[1]), max);
        StringBuffer sb = new StringBuffer();
        for (int i = 0, len = ip.length; i < len; i++) {
            if(max) {
                sb.append(Integer.parseInt(ip[i]) + masks[i]);
            }else {
                sb.append(Integer.parseInt(ip[i]) & masks[i]);
            }
            if (i != len - 1) {
                sb.append(".");
            }
        }
        return sb.toString();
    }
}


